/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.startup;

import cn.ac.iie.di.commons.httpserver.framework.server.HttpServer;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.configuration.Configuration;
import cn.ac.iie.di.wx.handler.WxFansCnt;
import cn.ac.iie.di.wx.handler.WxPictureUrl_cache_yizhuang;
import cn.ac.iie.di.wx.handler.WxPictureUrl_new;
import cn.ac.iie.di.wx.handler.WxPictureUrl_new_yizhuang;
import cn.ac.iie.di.wx.handler.WxPictureUrl_old;
import cn.ac.iie.di.wx.handler.WxPictureUrl_old_cache;
import cn.ac.iie.di.wx.handler.WxReadCnt;
import cn.ac.iie.di.wx.handler.WxRealIdQuery;
import cn.ac.iie.di.wx.killHanlder.KillHandler;
import cn.ac.iie.di.wx.mongoservice.MongoHelper;
import cn.ac.iie.di.wx.mongoservice.FansMongoThread;
import cn.ac.iie.di.wx.mongoservice.ReadCntDocinfoMongoThread;
import cn.ac.iie.di.wx.mongoservice.ReadCntWxmsgMongoThread;
import cn.ac.iie.di.wx.mongoservice.RealIdMongoThread;
import cn.ac.iie.di.wx.queueservice.WriteToReadCntFile;
import cn.ac.iie.di.wx.queueservice.WriteTofile;
import cn.ac.iie.di.wx.redis.RedisThread;
import cn.ac.iie.di.wx.redis.RedisUtil;
import cn.ac.iie.di.wx.timerTask.CountTask;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Timer;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Administrator
 */
public class Server {

    static HttpServer httpServer = null;
    static Logger logger = Logger.getLogger(Server.class.getName());

    public static void main(String[] args) {
        PropertyConfigurator.configure(ClassLoader.getSystemClassLoader().getResource("log4j.properties"));
        logger.info("log4j.properties has been configured");
        try {
            init();
            initCount();
            KillHandler killHandler = new KillHandler();
            killHandler.registerSignal("TERM");
            RedisThreadsStarts();
            MongoUpdateThreadStart();
//            WriteToFileThread();
//            WriteNrdToFileThread
            RedisUtil redisUtil = new RedisUtil((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_HOSTS), (String) RuntimeEnv.getParam(RuntimeEnv.REDIS_MASTER_NAME), Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_DB_NAME)));
            Timer timer = new Timer();
            CountTask countTask = new CountTask(redisUtil);
            timer.schedule(countTask, 1000, 1000);
            startup();
            logger.info("server has been started .");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

    public static void init() throws Exception {
        String configurationFileName = "cconfiguration.properties";
        Configuration conf = Configuration.getConfiguration(ClassLoader.getSystemClassLoader().getResource(configurationFileName).getPath());
        if (conf == null) {
            logger.error("reading " + configurationFileName + " is failed.");
        }
        try {
            RuntimeEnv.initialize(conf);///参数，
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXFANSCNTQLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXPICQLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXREADCNTLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.WXREALIDQLIMIT));
//            logger.info(RuntimeEnv.getParam(RuntimeEnv.MONGOCONNECTLIMIT));
            //创建龙存目录
            File file = new File((String) RuntimeEnv.getParam(RuntimeEnv.PICCACHE));
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            logger.info("init success");
        } catch (Exception ex) {
            logger.error("initializng runtime enviroment is failed for" + ex.getMessage());
        }
    }

    public static void initCount() throws IOException {
        String path = ClassLoader.getSystemClassLoader().getResource("cconfiguration.properties").getPath();
//        logger.info(ClassLoader.getSystemClassLoader().getResource("cconfiguration.properties").getPath());
        Properties prop = new Properties();
        prop.load(new FileInputStream(path));
        RuntimeEnv.wxFansCntQueryCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxFansCntQueryCount", "0")));
        RuntimeEnv.wxReadCntCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxReadCntCount", "0")));
        RuntimeEnv.wxRealIdQueryCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxRealIdQueryCount", "0")));
        RuntimeEnv.wxPictureUrlQueryCount = new AtomicInteger(Integer.parseInt(prop.getProperty("wxPictureUrlQueryCount", "0")));
        logger.info(ClassLoader.getSystemClassLoader().getResource("cconfiguration.properties").getPath());

    }

    public static void WriteToFileThread() {
        //写入文件进程
        WriteTofile gtofile = new WriteTofile(
                (String) RuntimeEnv.getParam(RuntimeEnv.WTPATH),
                (String) RuntimeEnv.getParam(RuntimeEnv.FNAME),
                "",
                "",
                RuntimeEnv.picUrlBlockingQueue);
        Thread gthread = new Thread(gtofile);
        gthread.start();
        logger.info("WriteToFileThread start");
    }

    public static void WriteNrdToFileThread() {
        WriteToReadCntFile cntFile = new WriteToReadCntFile(
                (String) RuntimeEnv.getParam(RuntimeEnv.WTPATH),
                (String) RuntimeEnv.getParam(RuntimeEnv.READCNTFNAME),
                "",
                "",
                RuntimeEnv.readCntMqBlockingQueue);
        Thread cnthread = new Thread(cntFile);
        cnthread.start();
    }

    public static void MongoUpdateThreadStart() throws Exception {
        //微信用户新库粉丝数更新
        String[] host_1 = new String[1];
        host_1 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_1 = new MongoHelper(host_1,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWTABLENAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWPASSWORD));
        FansMongoThread wxUserNewFansthread = new FansMongoThread(mongoHelper_1, RuntimeEnv.fansWxUserNewBlockingQueue);
        Thread t_1 = new Thread(wxUserNewFansthread);
        t_1.start();
        //微信用户老库粉丝数更新
        String[] host_2 = new String[1];
        host_2 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_2 = new MongoHelper(host_2,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDTABLENAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDPASSWORD));
        FansMongoThread wxUserOldFansthread = new FansMongoThread(mongoHelper_2, RuntimeEnv.fansWxUserOldBlockingQueue);
        Thread t_2 = new Thread(wxUserOldFansthread);
        t_2.start();
        //微信用户老库真实Id更新
        String[] host_3 = new String[1];
        host_3 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_3 = new MongoHelper(host_3,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDTABLENAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSEROLDPASSWORD));
        RealIdMongoThread wxUserNewRealIdthread = new RealIdMongoThread(mongoHelper_3, RuntimeEnv.realIdWxUserOldBlockingQueue);
        Thread t_3 = new Thread(wxUserNewRealIdthread);
        t_3.start();
        //微信用户xin库真实ID更新
        String[] host_4 = new String[1];
        host_4 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_4 = new MongoHelper(host_4,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWTABLENAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXUSERNEWPASSWORD));
        RealIdMongoThread wxUserOldRealIdthread = new RealIdMongoThread(mongoHelper_4, RuntimeEnv.realIdWxUserNewBlockingQueue);
        Thread t_4 = new Thread(wxUserOldRealIdthread);
        t_4.start();
        //微信消息老库阅读数更新
        String[] host_5 = new String[1];
        host_5 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXMSGOLDMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_5 = new MongoHelper(host_5,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGOLDDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGOLDTABLENAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGOLDUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGOLDPASSWORD));
        ReadCntDocinfoMongoThread wxmsgOldReadCntthread = new ReadCntDocinfoMongoThread(mongoHelper_5, RuntimeEnv.readCntDocinfoBlockingQueue, RuntimeEnv.readCntMqBlockingQueue);
        Thread t_5 = new Thread(wxmsgOldReadCntthread);
        t_5.start();
        //微信消息新库交互阅读数更新
        String[] host_6 = new String[1];
        host_6 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_6 = new MongoHelper(host_6,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWTABLENAME_INTERACTIVE),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWPASSWORD));
        ReadCntWxmsgMongoThread wxmsgNewIReadCntthread = new ReadCntWxmsgMongoThread(mongoHelper_6, RuntimeEnv.readCntWxmsgIBlockingQueue, RuntimeEnv.readCntMqBlockingQueue);
        Thread t_6 = new Thread(wxmsgNewIReadCntthread);
        t_6.start();
        //微信消息新库群发阅读数更新
        String[] host_7 = new String[1];
        host_7 = ((String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWMONGOHOSTS)).split(";");
        MongoHelper mongoHelper_7 = new MongoHelper(host_7,
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWDBNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWTABLENAME_GROUP),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWUSERNAME),
                (String) RuntimeEnv.getParam(RuntimeEnv.WXMSGNEWPASSWORD));
        ReadCntWxmsgMongoThread wxmsgNewGReadCntthread = new ReadCntWxmsgMongoThread(mongoHelper_7, RuntimeEnv.readCntWxmsgGBlockingQueue, RuntimeEnv.readCntMqBlockingQueue);
        Thread t_7 = new Thread(wxmsgNewGReadCntthread);
        t_7.start();
        logger.info("mongoThread start");
    }

    public static void RedisThreadsStarts() {
        RedisUtil redisUtil = new RedisUtil((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_HOSTS),
                (String) RuntimeEnv.getParam(RuntimeEnv.REDIS_MASTER_NAME),
                Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_DB_NAME)));
        RedisThread nrdRedisThread = new RedisThread(redisUtil, "nrd_", RuntimeEnv.wxReadCntCount);
        RedisThread nfansRedisThread = new RedisThread(redisUtil, "nfans_", RuntimeEnv.wxFansCntQueryLimit);
        RedisThread realIdRedisThread = new RedisThread(redisUtil, "uid_", RuntimeEnv.wxRealIdQueryCount);
//        RedisThread picRedisThread = new RedisThread(redisUtil, "pic_", RuntimeEnv.wxPictureUrlQueryCount);

        Thread nrdThread = new Thread(nrdRedisThread);
        nrdThread.start();
        Thread nfansThread = new Thread(nfansRedisThread);
        nfansThread.start();
        Thread realIdThread = new Thread(realIdRedisThread);
        realIdThread.start();
//        Thread picThread = new Thread(picRedisThread);
//        picThread.start();
    }

    public static void startup() {
        try {
            logger.info("startup");
            httpServer = HttpServer.getHttpServer(
                    (String) RuntimeEnv.getParam(RuntimeEnv.JETTY_SERVER),
                    Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.JETTY_PORT)),
                    Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.JETTY_THREADNUM)));
            httpServer.registerContext("/resources");
            httpServer.registerContextHandler("/resources", "/WxReadCnt", WxReadCnt.class);//阅读数
            httpServer.registerContextHandler("/resources", "/WxRealIdQuery", WxRealIdQuery.class);//真实ID
            httpServer.registerContextHandler("/resources", "/WxFansCnt", WxFansCnt.class);//粉丝数
            httpServer.startup();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }

    }
}
